﻿using FastMvc.Auth;
using FastMvc.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace FastMvc
{
    /// <summary>
    /// 基础Controller类，
    /// 封装登录信息等数据
    /// </summary>
    public class BaseController : ControllerBase
    {
        public BaseController()
        {
            
        }

        #region 登录用户信息
        public UserAuthInfo UserAuth { get; set; }

        public string UserId => UserAuth?.sUserId;

        public string UserName => UserAuth?.sUserName;

        public string OrgId => UserAuth?.sOrgId;

        public string OrgName => UserAuth?.sOrgName;

        public IEnumerable<string> Permissions => UserAuth == null ? new List<string>() : UserAuth.Permissions;
        #endregion

        #region 权限
        /// <summary>
        /// 检查当前用户是否有某权限
        /// </summary>
        /// <param name="permissionName"></param>
        protected void CheckPermission(string permissionName)
        {
            if (!string.IsNullOrEmpty(permissionName))
            {
                if (this.UserAuth != null
                    && this.UserAuth.Permissions != null
                    && !this.UserAuth.Permissions.Contains(permissionName))
                {
                    throw new FastMvc.Exceptions.UnAuthException($"无权限的调用，需求：[{permissionName}]");
                }
            }
        }

        /// <summary>
        /// 将用户的权限，设置给当前Controller以及所有的Service，Repository
        /// </summary>
        /// <param name="userAuth"></param>
        internal void SetUserAuth(UserAuthInfo userAuth)
        {
            this.UserAuth = userAuth;

            // 检查所有的Service， 下发权限信息
            // 字段
            var fileds = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            foreach (var f in fileds)
            {
                if (typeof(IJQService).IsAssignableFrom(f.FieldType))
                {
                    (f.GetValue(this) as IJQService).SetUserAuth(userAuth);
                }
            }
            // 属性
            var ps = this.GetType().GetProperties(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
            foreach (var f in ps)
            {
                if (typeof(IJQService).IsAssignableFrom(f.PropertyType))
                {
                    (f.GetValue(this) as IJQService).SetUserAuth(userAuth);
                }
            }
        }
        #endregion

        #region 一些公共方法
        /// <summary>
        /// 设置返回数据
        /// - Null的时候，返回success = false，code =1
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="SuccessMsg">默认成功字符串(获取数据成功)</param>
        /// <param name="errCode">默认错误代码（1）</param>
        /// <returns></returns>
        protected async Task<BaseResult<T>> SetResultNotNull<T>(T data, string SuccessMsg = "操作成功！", int errCode = 1)
        {
            if (data == null)
            {
                return await Task.FromResult(new BaseResult<T>()
                {
                    success = false,
                    code = errCode,
                    message = "操作失败！"
                });
            }
            else
            {
                return await Task.FromResult(new BaseResult<T>()
                {
                    success = true,
                    code = 0,
                    message = SuccessMsg,
                    data = data
                });
            }
        }
        #endregion
    }
}
